<script>
  const obj = {
    count: 0,
    addCount() {
      this.count++;
    },
  };

  Function.prototype.myBind = function (ctx, ...outerArgs) {
    ctx = [null, undefined].includes(ctx) ? globalThis : Object(ctx);
    const self = this;
    let Fn = function (...innerArgs) {
      const allArgs = [...outerArgs, ...innerArgs];
      let result = null;
      if (new.target === Fn) {
        result = new self(...allArgs);
      } else {
        result = self.apply(ctx, allArgs);
      }
      return result;
    };
    // if (this.prototype) {
    //   // 使用中介函数避免直接修改
    //   const Temp = function () {};
    //   Temp.prototype = this.prototype;
    //   Fn.prototype = new Temp();
    //   Fn.prototype.constructor = Fn;
    // }
    return Fn;
  };

  //   const bindFn = obj.addCount.myBind(obj, 11);
  //   bindFn();
  //   console.log('objCount', obj.count);

  function Person(name, age) {
    console.log('this--', this);
    this.name = name;
    this.age = age;
  }

  const p = {};

  const bindFn = Person.myBind(p);
  new bindFn('monica', 18);
  console.log(p);

  //   bind之后不能再次修改this的指向（箭头函数的底层实现原理依赖bind绑定this后不能再次修改this的特性），bind多次后执行，函数this还是指向第一次bind的对象
</script>
